﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using CommonUtils;
using Resources;
using EntityDataModel;

namespace LiveCPEProject.messages
{
    public partial class Messages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try {
                // If the user is NOT logged
                if (!Context.User.Identity.IsAuthenticated)
                {
                    Response.Redirect("~/login/Login.aspx");
                }

                if (!IsPostBack)
                {
                    LoadData();
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void LoadData()
        {
            try
            {
                RepeaterFriends.ItemDataBound += new RepeaterItemEventHandler(RepeaterFriends_ItemDataBound);
                
                RepeaterFriends.DataSource = FriendshipBLL.GetAllFriendsForUser(Context.User.Identity.Name);
                RepeaterFriends.DataBind();
                
                DataList1.DataSource = GetAllMessages(Context.User.Identity.Name);
                DataList1.DataBind();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        void RepeaterFriends_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                LinkButton lkb = ControlFinder.FindControl<LinkButton>(e.Item, "linkFriendForList");
                if (lkb.CommandArgument == TextBoxSender.Text)
                {
                    lkb.CssClass = "friendForList2";
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void Redirect_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect("~/wall/Wall.aspx?userName=" + ((LinkButton)sender).CommandArgument);
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void SelectFriendForMessage_Click(object sender, EventArgs e)
        {
            try
            {
                LinkButton lkb = (sender as LinkButton);
                TextBoxSender.Text = lkb.CommandArgument;
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void TextBoxMessage_Changed(object sender, EventArgs e)
        {
            try
            {
                TextBox tb = (sender as TextBox);
                Button bt = ControlFinder.FindControl<Button>(this, "ButtonMessage");
                if (bt != null)
                {
                    bt.CommandArgument = tb.Text;
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }


        protected void ButtonMessage_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBoxMessage.Text.Length > 0 && TextBoxSender.Text.Length > 0)
                {
                    if (TextBoxMessage.Text.Length > 150)
                    {
                        TextBoxMessage.Text = TextBoxMessage.Text.Substring(0, 150);
                    }
                    MessageBLL.SendPrivateMessage(Context.User.Identity.Name, TextBoxSender.Text, TextBoxMessage.Text);
                    TextBoxMessage.Text = "";
                }
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected List<Message> GetAllMessages(String userName)
        {
            try
            {
                List<Message> messages = MessageBLL.GetAllPrivateMessagesForUser(userName);
                foreach (Message m in messages)
                {
                    // Handle the publication date
                    if (int.Parse(m.PublicationAge) >= 60)
                    {
                        if (int.Parse(m.PublicationAge) >= 3600)
                        {
                            if (int.Parse(m.PublicationAge) >= 86400)
                            {
                                m.PublicationAge = Math.Floor(double.Parse(m.PublicationAge) / 86400.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeDaysAfter"); ;
                            }
                            else
                            {
                                m.PublicationAge = Math.Floor(double.Parse(m.PublicationAge) / 3600.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeHoursAfter");
                            }
                        }
                        else
                        {
                            m.PublicationAge = Math.Floor(double.Parse(m.PublicationAge) / 60.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeMinutesAfter");
                        }
                    }
                    else
                    {
                        m.PublicationAge += " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeSecondsAfter");
                    }
                }
                return messages;
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] GetUserNameList(string prefixText, int count, string contextKey)
        {
            try
            {
                String[] listUserNames = UserBLL.GetAllUserNames();
                return (from l in listUserNames where l.Contains(prefixText) select l).Take(count).ToArray();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }
    }
}